package com.mkyong.ws;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebService;

import com.mkyong.entity.Alphabet;

 
//Service Implementation
@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
 
	
	@Override
	@WebMethod
	public Alphabet getAlphabet() {
		Alphabet alphabet = new Alphabet();
		try {
			alphabet.setImages(getImages());
			alphabet.setSons(getSounds());
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return alphabet;
	}
	
	private List<byte[]> getImages() throws SQLException, ClassNotFoundException{
		Class.forName("org.gjt.mm.mysql.Driver");
	    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/jeux", "root", "root");
		List<byte[]> images = new ArrayList<byte[]>();
		String sql = "SELECT image FROM alphabet";
        Statement stmt = (Statement) conn.prepareStatement(sql);
        ResultSet resultSet = stmt.executeQuery(sql);
        

        while (resultSet.next()) 
        {
            byte[] img = resultSet.getBytes(1);
            images.add(img);
          }

        conn.close();
        return images;
	}
	
	private List<byte[]> getSounds() throws SQLException, ClassNotFoundException{
		Class.forName("org.gjt.mm.mysql.Driver");
	    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/jeux", "root", "root");
		List<byte[]> sounds = new ArrayList<byte[]>();
		String sql = "SELECT son FROM alphabet";
        Statement stmt = (Statement) conn.prepareStatement(sql);
        ResultSet resultSet = stmt.executeQuery(sql);
        

        while (resultSet.next()) 
        {
            byte[] son = resultSet.getBytes(1);
            sounds.add(son);
          }

        conn.close();
        return sounds;
	}

}